/*


setInterval(() => {
    location.reload();
}, 600000);
*/

setInterval(() => {
    location.reload();
}, 3600000);


var fail_number = 0;
chrome.runtime.onMessage.addListener(async (msg, sender) => {

    console.log(msg);

   /* if(fail_number % 10 ===5){
        setTimeout(() => {
            location.reload()
        },1000);
    }
    if(fail_number > 30){
        console.log("shein block");
        fail_number = 0;
        var type = "sheinblock_yn";
        chrome.runtime.sendMessage({ data: {type }, close: false });
        setTimeout(() => {
            location.reload()
        },1000);
    }
 */
    var url = "https://s1.shein.com/bff-api/product/get_goods_detail_realtime_data?_ver=1.1.8&_lang=en&goods_id=" + msg.data.goods_id + "&mallCode=1&isUserSelectedMallCode=0&isQueryIsPaidMember=1&isQueryCanTrail=0&isHideEstimatePriceInfo=0&specialSceneType=0&countryId=226";
    var fail_time = 0;
    fetch(url, {
        method: 'GET',
        headers: {
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'anti-in': '0_1.9.1_c38d61_-qx5b0yIhYmNyQg4_nzJw02_XsG7Wbct9SKxL8BesDsAtw5l6XjE4uY2weB9dAatfxMSTdlKbd01lOIVfhNNpdD137c835Lx4N4DCfMSfp66DcYAsPXeyIXkj6hz0reu9PPJ-i9Ry-ZcN2QH_fSWLo5hd5uQECpV0q-zBPYRkrx2LUddIH1SEyjz9DNwu173w-XOcJ0sVk_ubuqPT4t3HK7g-8SiJodsQcItiljQVsOCayA9OoYE14OarnEA2HZXsIqKvxi7aidKvdwY7KteHbcLfxjF2_GwfxFfTY9csb6o0b6HX9MvXvcP05Ho2pepxfZ3XTeqw4PYkyHkKqVDxqBwg1xSJKlEOKyXD3SkCaGcVNrmEfP8_6VioIYou7MCZ0TcH6iVDiN5q2AbhJ1XshURP7yOqnZLmjdf8G2l_XfOQ3SHgIIQlG9JFYKoNkZ2MjKdquUeEpPjJ5pR_aH1QrYgeHv9z3AWK2jbjQ4bsfbO0uM_4ZK_iI_qGhaC_QRrOa9RCu_aG2ilaoiDocXnrKv5jUamfWt-IySkyjAikHFo0rybUKZehMiIhoRoTWfeJSE62J0vRjR76_TgrG1XerIZyAG6HNa-Ny1wi_3ZRqsA4RrM5WWmYIrH_MfsI2q1waNo1JJZO9EiXgKFd3kCQJseDQFFf-7CR8uJDYYd7C9i0iGwk8gOyXmswakoO2qKQD_ZaLia0mfiHOd4kXSAfJqNNyqG_vTjeSEXNmZRwN4cGoln1A8FkBEKsMUc6uY7m',
            'armortoken': 'T0_3.3.0_HrzEkoY1JjaE3mp_fOTINtzBb-h-EkHI0vvSoOmZuZcgwjbqAfmTkQm-fjEVe-gXeN9a2jl02nli0HXVAdgRVvXqDIfiPnUWKtA5HvEwH3RAxPc4sBDMcXOJpkm0tW_mqFiuAGw6zghfuIDcFn_Vuyd5REj4JUH6F8gsPL3qzJjakISTWpoJfszsJHKxxwy7_1747379001280',
            'priority': 'u=1, i',
            'referer': 'https://s1.shein.com/sheinlevel?type=local',
            'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
            // Add other needed headers from the second request here as necessary
        },
        credentials: 'include' // 如果需要携带 cookie
    })
        .then(response => {
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            return response.json();
        })
        .then(data => {
            console.log(data);
            doWitdhDataJob(data,msg.data.id);
        })
        .catch(error => {
            fail_time ++;
            console.log("fail_time:"+fail_time);
            if(fail_time >=5){
                fail_time = 0;
                console.log("sheinblock_sheinlevel");
                var type = "sheinblock_sheinlevel";
                chrome.runtime.sendMessage({ data: {type }, close: false });
                setTimeout(() => {
                     location.reload()
                },100000);
            }

        });


})

function getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return r[2];
    }
    return 0;
 }
 console.log("shein stock")


$(document).ready(function() {
    getStockByFetch();
});


function doWitdhDataJob(jsonObject,id){

    if(jsonObject['code']=="200301"){

        var type = "sheindetaildel";
        var data={}
        data.id = id
        console.log(data);
        chrome.runtime.sendMessage({ data: {type,data }, close: false })
        setTimeout(function() {
            window.close();
        }, 10000);
    }else if(jsonObject['info']['saleAttr'] && jsonObject['info']['saleAttr']['multiLevelSaleAttribute'] && jsonObject['info']['saleAttr']['multiLevelSaleAttribute']['sku_list']){
        var sku_list = jsonObject['info']['saleAttr']['multiLevelSaleAttribute']['sku_list'];
        console.log(sku_list);

        var stock_map = {};
        var index = 0;
        sku_list.forEach((item) => {
            if(item['sku_sale_attr'] && item['sku_sale_attr'].length>0){
                stock_map[item['sku_sale_attr'][0]['attr_value_name']] = item['stock'];
            }else{
                stock_map[index] = item['stock'];
            }
            index++;

        })

        var type = "sheinstock";
        console.log('sheinstock send.');
        chrome.runtime.sendMessage({ data: {type,id, stock_map}, close: false });

        setTimeout(function() {

            window.close();
        }, 10000);
    }else if(jsonObject['info']['productInfo']['stock']==0){

        var type = "sheinstock";
        console.log('sheinstock send no stock.');

        var stock_map = {};
        stock_map[0] = 0;
        chrome.runtime.sendMessage({ data: {type,id, stock_map}, close: false });
        setTimeout(function() {
            window.close();
        }, 10000);
    }

    console.log(stock_map);
}
function  getStockByFetch(msg){
    var id = getQueryString("bid");
    if(id){
        if(location.href.includes("www.shein.com.hk/risk/action/limit")){
            setTimeout(function() {
                window.close();
            }, 5000);
            return;
        }else{
            setTimeout(function() {
                window.close();
            }, 20000);
        }
        var bodyContent = $('body').text();
        console.log(bodyContent)

        var jsonObject = JSON.parse(bodyContent);
        doWitdhDataJob(jsonObject,id);
    }
}

